package com.xiaofen.license.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

	private static ApplicationContext factory;

	/** 从外部设置对象工厂 */
	public static void setFactory(ApplicationContext factory) {
		if (SpringUtils.factory == null) {
			SpringUtils.factory = factory;
		}
	}

	public static Object getBean(String beanName) throws BeansException {
		if (factory.containsBean(beanName))
			return factory.getBean(beanName);
		else
			return null;
	}

	public static <T> T getBean(Class<T> classType) throws BeansException {
		return factory.getBean(classType);
	}

	public static Environment getEnvironment() {
		return factory.getEnvironment();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringUtils.factory == null) {
			SpringUtils.factory = applicationContext;
		}
	}
}